package cn.zhaozhiqi.interceptor;

import cn.zhaozhiqi.service.impl.LoginServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    LoginServiceImpl loginService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        //判断当前请求是否是已经登录的人在操作!!!
        // 1.从请求头中获取前端传递过来的token串
        String token = request.getHeader("token");
        //2.如果token是空的，滚去登录
        if ("null".equals(token)){
            PrintWriter writer =response.getWriter();
            //没有登录，请去登录
            writer.write( "{\"code\":\"401\",\"success\":false}");
            return false;//阻止拦截器往下走
        }
        //3.如果token不为空，判断是否登录失效了
        if (!loginService.getMap().containsKey(token)){//containsKey()判断是否包含有此key
            PrintWriter writer =response.getWriter();
        //4.如果失效了，滚去登录
            writer.write( "{\"code\":\"401\",\"success\":false}");
            return false;//阻止拦截器往下走
        }
        //5.否则，拦截器放行
        return true;



    }
}
